<script setup>
import { ref } from 'vue'
import 'vant/es/toast/style'
import { showFailToast } from 'vant'
import { useRouter } from 'vue-router'
import { useCartStore } from '@/stores/cart.js'

defineOptions({
  name: 'cartList'
})
const cartStore = useCartStore()

const router = useRouter()

const checkList = ref(
  cartStore.cartList.filter((item) => item.is_checked).map((item) => item.id)
)
const togChecked = (id) => {
  checkList.value.includes(id)
    ? checkList.value.splice(checkList.value.indexOf(id), 1)
    : checkList.value.push(id)
  cartStore.togcheck(checkList.value)
  selAll.value = checkList.value.length === cartStore.cartList.length
}

const selAll = ref(
  checkList.value.length
    ? checkList.value.length === cartStore.cartList.length
    : false
)

const togAll = () => {
  cartStore.cartList.map((item) => (item.is_checked = Number(selAll.value)))
  checkList.value = selAll.value
    ? cartStore.cartList.map((item) => item.id)
    : []

  cartStore.togcheck(checkList.value)
}
const onSubmit = () => {
  if (checkList.value.length) router.replace('/preview')
  else showFailToast('请选择商品进行结算')
}
</script>

<template>
  <div>
    <cartItem
      v-for="item in cartStore.cartList"
      :key="item.id"
      :item="item"
      @togChecked="togChecked"
    ></cartItem>

    <van-submit-bar
      :price="cartStore.totalPrice * 100"
      button-text="结算"
      @submit="onSubmit"
      class="bar"
    >
      <van-checkbox @click="togAll" checked-color="red" v-model="selAll"
        >全选</van-checkbox
      >
    </van-submit-bar>
  </div>
</template>

<style scoped lang="scss">
.bar {
  position: fixed;
  bottom: 55px;
}
</style>
